﻿using System;
using System.Collections.Generic;
using System.Data.Entity; // needed for lambda includes
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TheCup.Controllers
{
    public class TeeController : Controller
    {
        string[] Genders = new string[] { "Herre", "Dame" };

        ApiControllers.TeeController tc = new ApiControllers.TeeController();
        ApiControllers.CourseController cc = new ApiControllers.CourseController();

        public ActionResult Index()
        {
            return View("Index", tc.Get());
        }

        public ActionResult Details(int id)
        {
            Tee e = tc.Get(id);
            return View(e);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">The CourseId you want to create Tee's for</param>
        /// <returns></returns>
        public ActionResult CreateForCourse(int id)
        {
            ViewBag.Courses = cc.Get();
            ViewBag.Genders = Genders;
            
            Tee e = new Tee();
            e.CourseId = id;
            e.IsActive = true;
            
            return View(e);
        }

        /// <summary>
        /// Finds an old tee with valid index and par and transfers it to a new Tee
        /// </summary>
        /// <param name="tees"></param>
        /// <param name="newTee"></param>
        private void TransferTeeInfo(IEnumerable<Tee> tees, Tee newTee)
        {
            foreach (Tee t in tees)
            {
                if (t.Idx1 > 0 && t.Par1 > 0)
                {
                    for (int i = 1; i < 19; i++)
                    {
                        newTee.SetIdx(i, t.GetIdx(i));
                        newTee.SetPar(i, t.GetPar(i));
                    }
                    break; // jumps out of loop?
                }
            }
        }

        [HttpPost]
        public ActionResult Create(Tee e)
        {
            // Transfer old tee info
            IEnumerable<Tee> tees = tc.GetForCourse(e.CourseId).ToList();
            this.TransferTeeInfo(tees, e);

            Tee newTee = tc.Post(e);

            return RedirectToAction("Edit", new { id = newTee.Id });
        }

        public ActionResult Edit(int id)
        {
            Tee e = tc.Get(id);
            ViewBag.Genders = Genders;
            return View(e);
        }

        [HttpPost]
        public ActionResult Edit(Tee e)
        {
            tc.Put(e.Id, e);
            e = tc.Get(e.Id);
            return RedirectToAction("Details", "Course", new { id = e.Course.Id });
        }
    }
}
